package com.farm.learn.utils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;


import org.apache.commons.lang.StringUtils;

import com.farm.authority.service.UserServiceInter;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.result.DataResult;
import com.farm.learn.domain.Major;
import com.farm.learn.domain.Usermajor;
import com.farm.learn.service.MajorServiceInter;
import com.farm.learn.service.UsermajorServiceInter;
import com.farm.util.spring.BeanFactory;

public class UserMajorLoader implements Runnable {

	private static boolean isRun = false;
	private static List<String> majorids;
	private static List<String> userids;
	private static int all = 0;
	private static int i = 0;
	private static String message;

	private static UserServiceInter userServiceImpl = (UserServiceInter) BeanFactory.getBean("userServiceImpl");
	private static MajorServiceInter majorServiceImpl = (MajorServiceInter) BeanFactory.getBean("majorServiceImpl");
	private static UsermajorServiceInter userMajorServiceImpl = (UsermajorServiceInter) BeanFactory
			.getBean("usermajorServiceImpl");

	/**
	 * 加载更新某个专业的全部用户学习记录
	 * 
	 * @param majorid
	 */
	public UserMajorLoader(String majorid) {
		if (isRun) {
			throw new RuntimeException("服务正在运行中:UserMajorLoader");
		}
		majorids = new ArrayList<String>();
		majorids.add(majorid);
		userids = new ArrayList<String>();
		message = "";
	}

	public void run() {
		if (!isRun) {
			try {
				isRun = true;
				if (userids == null || userids.size() <= 0) {
					userids = userServiceImpl.getAllLiveUserIds();
				}
				all = majorids.size() * userids.size();
				i = 1;
				for (String majorid : majorids) {
					Major major = majorServiceImpl.getMajorEntity(majorid);
					for (String userid : userids) {
						i++;
						loadUserMajorInfo(major, userid);
					}
				}
			} catch (Exception e) {
				message = e.getMessage();
			} finally {
				isRun = false;
			}
		}
	}

	/**
	 * 合计用户专业学习信息
	 * 
	 * @param major
	 * @param userid
	 * @throws SQLException
	 */
	public static void loadUserMajorInfo(String classid, String userid) throws SQLException {
		Set<String> majorids = majorServiceImpl.getMajorsByClassid(classid);
		for (String majorid : majorids) {
			Major major = majorServiceImpl.getMajorEntity(majorid);
			loadUserMajorInfo(major, userid);
		}
	}

	/**
	 * 合计用户专业学习信息
	 * 
	 * @param major
	 * @param userid
	 * @throws SQLException
	 */
	public static void loadUserMajorInfo(Major major, String userid) throws SQLException {
		// TODO 查询专业信息，专业课程，用户课程学习记录
		DataQuery q = DataQuery.getInstance(1, "a.CLASSID as CLASSID,PROCESS,USETIME,STIME,ETIME,LTIME,PSTATE",
				"WLP_L_MAJORCLASS a LEFT JOIN WLP_U_USERCLASS b ON a.CLASSID = b.CLASSID AND b.USERID = '" + userid
						+ "'");
		q.addRule(new DBRule("a.MAJORID", major.getId(), "="));
		q.setPagesize(1000);
		q.setNoCount();
		DataResult result = q.search();
		//全部课程
		Set<String> allClass=new HashSet<String>();
		//已完成课程数量
		Set<String> compeletClass=new HashSet<String>();
		//学习中的课程
		Set<String> leanningClass=new HashSet<String>();
		// 开始时间
		String stime = "99999999999999";
		// 结束时间
		String etime = "00000000000000";
		// 最近学习时间
		String ltime = "00000000000000";
		// 未学习课程数量
		int nnum = 0;
		// 学习时长
		int usetime = 0;
		// 百分比合計
		Integer allprocess = 0;
		for (Map<String, Object> node : result.getResultList()) {
			allClass.add((String)node.get("CLASSID"));
			// 状态2:学习中,3:完成
			String pstate = (String) node.get("PSTATE");
			if (StringUtils.isNotBlank(pstate)) {
				if (pstate.equals("3")) {
					compeletClass.add((String)node.get("CLASSID"));
				} else {
					leanningClass.add((String)node.get("CLASSID"));
				}
			} else {
				nnum++;
			}
			String classEtime = (String) node.get("ETIME");
			if (StringUtils.isNotBlank(classEtime) && etime.compareTo(classEtime) < 0) {
				etime = classEtime;
			}
			String classLtime = (String) node.get("LTIME");
			if (StringUtils.isNotBlank(classLtime) && ltime.compareTo(classLtime) < 0) {
				ltime = classLtime;
			}
			String classStime = (String) node.get("STIME");
			if (StringUtils.isNotBlank(classStime) && stime.compareTo(classStime) > 0) {
				stime = classStime;
			}
			Integer cusetime = (Integer) node.get("USETIME");
			if (cusetime != null) {
				usetime = cusetime + usetime;
			}
			Integer cprocess = (Integer) node.get("PROCESS");
			if (cprocess != null) {
				allprocess = allprocess + cprocess;
			}
		}
		int snum=0;
		for(String id:leanningClass) {
			if(!compeletClass.contains(id)) {
				snum++;
			}
		}
		if (snum + compeletClass.size() > 0 && allClass.size() > 0) {
			Usermajor usermajor = new Usermajor();
			usermajor.setUserid(userid);
			usermajor.setMajorid(major.getId());
			// 全部课程数量
			usermajor.setAnum(allClass.size());
			// 已完成课程数量
			usermajor.setCnum(compeletClass.size());
			// 结束时间
			usermajor.setEtime(etime);
			// 最近学习时间
			usermajor.setLtime(ltime);
			// 未学习课程数量
			usermajor.setNnum(nnum);
			// 完成百分比
			usermajor.setProcess(allprocess / allClass.size());
			// 状态
			usermajor.setPstate(compeletClass.size() >= allClass.size() ? "3" : "2");
			// 学习中课程数量
			usermajor.setSnum(snum);
			// 开始时间
			usermajor.setStime(stime);
			// 学习总耗时（分）
			usermajor.setUsetime(usetime);
			userMajorServiceImpl.deleteUsermajor(userid, major.getId());
			userMajorServiceImpl.insertUsermajorEntity(usermajor);
		}
	}

	public static boolean isRun() {
		return isRun;
	}

	public static List<String> getMajorids() {
		return majorids;
	}

	public static List<String> getUserids() {
		return userids;
	}

	public static int getAll() {
		return all;
	}

	public static int getI() {
		return i;
	}

	public static String getMessage() {
		return message;
	}

}
